using System.Collections.Generic;
using System.Linq;
using Arcane.Source.Data;
using Godot;

namespace Arcane.Source.TileMatch.Tile;

public class RuneTile : GravityTile
{
    private Element _element;
    private int _level;

    public Element Element => _element;
    public int Level => _level;

    public RuneTile(Element element, int level, IPhase phase) : base(phase)
    {
        _element = element;
        _level = level;
    }
    
    public RuneTile(Element element, int level) : this(element, level, new Droping { tick = 0 }) {}

    public void Reset(Element element, int level)
    {
        _element = element;
        _level = level;
    }

    public override bool Matches(ITile other)
    {
        return other is RuneTile rune && _element == rune._element;
    }

    public override bool Interactable() => IsIdle();

    public override bool Swapable(ITile tile)
    {
        return tile is RuneTile rune && rune.IsIdle();
    }

    public override void OnMatch(Match match, TilePos pos, List<TilePos> matchedPos)
    {
        var levelUp = Mathf.Clamp(matchedPos.Count - 3, 0, int.MaxValue);

        if (levelUp > 0)
        {
            matchedPos.Remove(pos);

            _level += levelUp;
            _level = Mathf.Clamp(_level, 0, 2);

            match.EmitCellUpdate(this, pos);
        }
        
        match.RemoveTilesUnchecked(matchedPos);
    }
}